interface CacheItem<T> {
  data: T;
  timestamp: number;
  expiry: number;
}

class DataCache {
  private cache = new Map<string, CacheItem<any>>();
  private readonly DEFAULT_TTL = 5 * 60 * 1000; // 5分钟

  set<T>(key: string, data: T, ttl: number = this.DEFAULT_TTL): void {
    const item: CacheItem<T> = {
      data,
      timestamp: Date.now(),
      expiry: Date.now() + ttl,
    };
    this.cache.set(key, item);
  }

  get<T>(key: string): T | null {
    const item = this.cache.get(key);
    if (!item) return null;

    if (Date.now() > item.expiry) {
      this.cache.delete(key);
      return null;
    }

    return item.data as T;
  }

  has(key: string): boolean {
    const item = this.cache.get(key);
    if (!item) return false;

    if (Date.now() > item.expiry) {
      this.cache.delete(key);
      return false;
    }

    return true;
  }

  delete(key: string): boolean {
    return this.cache.delete(key);
  }

  clear(): void {
    this.cache.clear();
  }

  // 清理过期的缓存项
  cleanup(): void {
    const now = Date.now();
    for (const [key, item] of this.cache.entries()) {
      if (now > item.expiry) {
        this.cache.delete(key);
      }
    }
  }

  // 获取缓存统计信息
  getStats() {
    return {
      size: this.cache.size,
      keys: Array.from(this.cache.keys()),
    };
  }
}

// 创建全局缓存实例
export const dataCache = new DataCache();

// 自动清理过期缓存（每5分钟执行一次）
setInterval(() => {
  dataCache.cleanup();
}, 5 * 60 * 1000);

// 工具函数：生成缓存键
export const getCacheKey = {
  taskDashboard: (managerId: number, includeComparison: boolean = false) => 
    `task_dashboard_${managerId}_${includeComparison}`,
  
  reminderSettings: (managerId: number) => 
    `reminder_settings_${managerId}`,
  
  serviceProgress: (managerId: number, serviceId: number) => 
    `service_progress_${managerId}_${serviceId}`,
  
  progressComparison: (managerId: number, serviceId: number) => 
    `progress_comparison_${managerId}_${serviceId}`,
};